package com.example.makerspace.utils;

import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Optional;

public class JGitUtil {

    private static final Logger log = LoggerFactory.getLogger(JGitUtil.class);

    private static CredentialsProvider provider = new UsernamePasswordCredentialsProvider("root", "Ls422327276");

    public static Git openRepo(String localPath) {
        Git git = null;
        try {
            Repository repository = new FileRepositoryBuilder()
                    .setGitDir(new File(localPath, ".git"))
                    .build();
            git = new Git(repository);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return git;
    }

    public static void init(String localPath) throws GitAPIException {
        Git git = openRepo(localPath);
        git.init().setDirectory(new File(localPath)).call();
    }

    public static void add(String localPath, String... filenames) throws GitAPIException {
        Git git = openRepo(localPath);
        for (String filename : filenames) {
            git.add().addFilepattern(Optional.ofNullable(filename).orElse(".")).call();
        }
    }

    public static void rm(String localPath, String... filenames) throws GitAPIException {
        Git git = openRepo(localPath);
        for (String filename : filenames) {
            git.rm().addFilepattern(filename).call();
        }
    }

    public static void commit(String localPath, String commitInfo) throws GitAPIException {
        Git git = openRepo(localPath);
        git.commit().setMessage(Optional.ofNullable(commitInfo).orElse("default commit info")).call();
    }

    public static void mv(String localPath, String sourcePath, String targetPath, File file) {
        System.out.println(sourcePath);
        try {
            File newDir = new File(targetPath);
            if (!newDir.exists()) {
                newDir.mkdirs();
            }
            File newFile = new File(newDir, file.getName());
            boolean success = file.renameTo(newFile);
            if (success) {
                add(localPath, ".");
                rm(localPath, sourcePath);
                commit(localPath, "file moved to new directory");
                push(localPath);
            } else {
                // 处理错误
                log.error("文件移动异常！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void status(String localPath) throws GitAPIException {
        Git git = openRepo(localPath);
        Status status = git.status().call();
        // 这里可以根据需要打印或处理状态信息
        log.info("Added files: {}", status.getAdded());
        log.info("Changed files: {}", status.getChanged());
        // 其他状态信息...
    }

    public static void pull(String localPath) throws GitAPIException {
        Git git = openRepo(localPath);
        git.pull().call();
    }

    public static void push(String localPath) throws GitAPIException {
        Git git = openRepo(localPath);
        git.push().setPushAll().setCredentialsProvider(provider).call();
    }

    public static void remoteAdd(String localPath, String remoteName, String remoteUrl) throws GitAPIException {
        Git git = openRepo(localPath);
        RemoteAddCommand remoteAddCommand = git.remoteAdd();
        remoteAddCommand.setName(remoteName);
        URIish urIish = new URIish();
        urIish.setPath(remoteUrl);
        remoteAddCommand.setUri(urIish);
        remoteAddCommand.call();
    }

    public static void remoteSetUrl(String localPath, String remoteName, String newRemoteUrl) throws GitAPIException {
        Git git = openRepo(localPath);
        RemoteSetUrlCommand remoteSetUrlCommand = git.remoteSetUrl();
        remoteSetUrlCommand.setRemoteName(remoteName);
        URIish urIish = new URIish();
        urIish.setPath(newRemoteUrl);
        remoteSetUrlCommand.setRemoteUri(urIish);
        remoteSetUrlCommand.call();
    }

//    public static void cherryPick(String localPath, String commitId) throws GitAPIException {
//        Git git = openRepo(localPath);
//        CherryPickCommand cherryPickCommand = git.cherryPick();
//        cherryPickCommand.setCommit(commitId);
//        cherryPickCommand.call();
//    }

    public static void reset(String localPath, String mode) throws GitAPIException {
        Git git = openRepo(localPath);
        ResetCommand resetCommand = git.reset();
        resetCommand.setMode(ResetCommand.ResetType.valueOf(mode));
        resetCommand.call();
    }

    public static void clone(String remoteUrl, String localPath) throws GitAPIException {
        CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI(remoteUrl);
        cloneCommand.setDirectory(new File(localPath));
        cloneCommand.setCredentialsProvider(provider);
        cloneCommand.call();
    }

    public  static  void  pullProject(String localPath){
        Git git=null;
        try {
            git = Git.open(new File(localPath));
            RemoteAddCommand remoteAddCommand = git.remoteAdd();
            remoteAddCommand.setName("origin");
            remoteAddCommand.setUri(new URIish("http://119.45.199.13:8089/test/qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq.git"));
            remoteAddCommand.call();
            PullCommand pull = git.pull();
            // 添加所有更改
            pull.setRemoteBranchName("master");
            UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("root","Ls422327276");
            pull.setCredentialsProvider(credentialsProvider);
            pull.call();
//            String branchToMerge = "origin/master";
//            RevWalk revWalk = new RevWalk(git.getRepository());
//            System.out.println(git.getRepository());
//            System.out.println(git.getRepository().resolve(branchToMerge));
//            RevCommit commitToMerge = revWalk.lookupCommit(git.getRepository().resolve(branchToMerge));
//
//            // 执行合并
//            MergeCommand merge = git.merge();
//            merge.include(commitToMerge);
//            merge.setStrategy(MergeStrategy.RESOLVE); // 可以根据需要选择合并策略
//            merge.call();
        } catch (GitAPIException | IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public  static  void  commitProject(String localPath, String commitMessage) throws GitAPIException, IOException {
        Git git=null;
        git = Git.open(new File(localPath));
        AddCommand addCommand = git.add();
        addCommand.addFilepattern(".").call();
        JGitUtil.commit(localPath, commitMessage);
    }

        public static void main(String[] args) throws IOException, URISyntaxException, GitAPIException {
            String localPath = "D:\\my-project\\zqyypt_web";  // 替换为本地仓库路径

            Git git=null;


             //初始化仓库（如果是新仓库）
            JGitUtil.init(localPath);
            //添加多个文件到暂存区
             pullProject(localPath);
            // 提交更改

       //   commitProject(localPath, pushDTO.getCommitMessage());

            JGitUtil.push(localPath);
            // 推送更改到 GitLab

        }

    }
